package http

import (
	"bytes"
	"fmt"
	"net/http"
)

func SendPost(url string, body []byte) (*http.Response, error) {
	if body == nil {
		body = []byte{}
	}
	request, err := http.NewRequest("POST", url, bytes.NewBuffer(body))
	if err != nil {
		fmt.Printf("Error creating request: %v\\n", err)
		return nil, fmt.Errorf("error creating request:%w", err)
	}

	// 设置请求的 Content-Type 为 application/json
	request.Header.Set("Content-Type", "application/json")

	// 发送请求
	client := &http.Client{}
	response, err := client.Do(request)
	if err != nil {
		fmt.Printf("Error sending request: %v\\n", err)
		return nil, fmt.Errorf("error sending request:%w", err)
	}

	return response, nil
}

func HttpError(w http.ResponseWriter, err string, code int) {
	AllowCrossRegion(w)
	http.Error(w, err, code)
}

func AllowCrossRegion(w http.ResponseWriter) {
	w.Header().Set("Access-Control-Allow-Origin", "*")
	w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
	w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
}

